<!-- TODO 权限重构 -->
<template>
  <div class="product-list-container" v-loading="loading">
    <div
      class="base-list-header-seach bg-w mar-b-12"
      v-if="tableSetting.needSearch"
    >
      <form onsubmit="return false;">
        <div class="seach task-span1 task-flex task-ai guide-box">
          <div style="position: relative;"></div>

          <el-input
            v-model="searchModel.keyword"
            class="base-with-input task-ml12 mar-r-12"
            :placeholder="tableSetting.searchPlaceholder"
            v-trim:blur
          >
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
            <el-button
              type="primary"
              slot="append"
              @click="
                searchModel.pageNum = 1;
                search();
              "
              native-type="submit"
            >{{$t('common.base.search')}}</el-button
            >
          </el-input>
          <el-button type="plain-third" @click="resetParams"
          >{{$t('common.base.reset')}}</el-button
          >

          <div class="guide-box" v-if="tableSetting.needAdvancedSearch">
            <div
              id="product-product-list-2"
              class="advanced-search-visible-btn bg-w"
              @click.self.stop="panelSearchAdvancedToggle"
            >
              <i class="iconfont icon-filter"></i>
              {{$t('common.base.advancedSearch')}}
            </div>
          </div>
        </div>
      </form>
    </div>

    <div style="background: #fff;padding: 10px 10px 0">
      <base-selection-bar
        ref="baseSelectionBar"
        v-model="multipleSelection"
        @toggle-selection="toggleSelection"
        @show-panel="() => (multipleSelectionPanelShow = true)"
      />
    </div>

    <div id="product-product-list-1" class="bg-w">
      <!-- 功能模块 s -->
      <div
        class="operation-bar-container box-12"
        v-if="
          tableSetting.needSelect ||
            tableSetting.needExport ||
            tableSetting.needExportAll ||
            tableSetting.needImport ||
            tableSetting.addFnc ||
            tableSetting.delFnc
        "
      >
        <div class="action-button-group flex-x bg-w">
          <div class="flex-1">
            <el-button
              type="primary"
              v-if="tableSetting.addFnc"
              @click="addFnc"
            ><i class="iconfont icon-add2"></i>{{ tableSetting.addFncText }}
            </el-button>
            <el-button
              v-if="tableSetting.tableSelect && tableSetting.delFnc"
              type="plain-third"
              @click="delFnc"
            >
              <i class="iconfont icon-delete"></i>{{ tableSetting.delFncText }}
            </el-button>
          </div>
          <el-dropdown
            trigger="hover"
            v-if="
              tableSetting.needSelect ||
                tableSetting.needExport ||
                tableSetting.needExportAll ||
                tableSetting.needImport
            "
          >
            <div class="task-ai task-flex task-font14 task-c6 cur-point bg-w">
              <span class="task-mr4 task-ml4">{{$t('common.base.moreOperator')}}</span>
              <i class="iconfont icon-fdn-select task-icon"></i>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="tableSetting.needImport">
                <div @click="openDialog('importProduct')">{{$t('common.base.import')}}</div>
              </el-dropdown-item>
              <el-dropdown-item v-if="tableSetting.needExport">
                <div @click="exportFn(false)">{{$t('common.base.export')}}</div>
              </el-dropdown-item>
              <el-dropdown-item v-if="tableSetting.needExportAll">
                <div @click="exportFn(true)">{{$t('common.base.exportAll')}}</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- 选择列 -->
          <div class="guide-box mar-l-25" v-if="tableSetting.needSelect">
            <div
              :class="[
                'task-ai',
                'task-flex',
                'task-font14',
                'task-c6',
                'cur-point',
                'task-width103',
              ]"
              @click="openDialog('select')"
            >
              <span class="task-mr4 task-ml4">{{$t('common.base.choiceCol')}}</span>
              <i class="iconfont icon-fdn-select task-icon"></i>
            </div>
          </div>
        </div>
      </div>
      <!-- 功能模块 e -->
      <div class="box-12-r-l bg-w pad-l-16 pad-r-16">
        <el-table
          stripe
          :data="page.list"
          :highlight-current-row="false"
          :border="true"
          @select="handleSelection"
          @select-all="handleSelectionAll"
          @header-dragend="headerDragend"
          @sort-change="sortChange"
          class="base-list-table common-list-table bg-w"
          header-row-class-name="common-list-table-header taks-list-table-header"
          ref="multipleTable"
          row-key="id"
          :tree-props="{ children: 'children' }"
          v-if="columns.length"
        >
          <el-table-column
            type="selection"
            v-if="tableSetting.tableSelect"
            width="48"
            align="center"
          ></el-table-column>
          <template v-for="(column, index) in columns">
            <el-table-column
              v-if="column.show"
              :key="`${column.field}_${index}`"
              :label="column.label"
              :prop="column.field"
              :width="column.width"
              :class-name="tableColumnClassName(column)"
              :min-width="column.minWidth || '120px'"
              :sortable="column.sortable"
              :show-overflow-tooltip="
                column.field !== 'name' &&
                  column.fieldName !== 'productPic' &&
                  column.field !== 'doSome'
              "
              :align="column.align"
              :fixed="column.fixed ? column.fixed : false"
            >
              <template slot-scope="scope">
                <!-- 服务资源相关 s-->
                <template v-if="column.field === 'teamLeaders'">
                  <span>{{ scope.row[column.field] | teamLeadersFilter }}</span>
                </template>
                <template v-else-if="column.field === 'tagPlaceList'">
                  <span>{{
                    scope.row[column.field] | tagPlaceListFilter
                  }}</span>
                </template>
                <template v-else-if="column.field === 'teamLeadersPhone'">
                  <span>{{
                    scope.row.teamLeaders.length
                      ? scope.row.teamLeaders[0].cellPhone
                      : ''
                  }}</span>
                </template>
                <!-- 针对特殊表单字段 -->
                <template v-else-if="column.tableShow">
                  {{ column.tableShow(scope.row, column) }}
                </template>
                <template v-else-if="column.field === 'teamLeadersWork'">
                  <span>{{
                    scope.row.teamLeaders.length
                      ? scope.row.teamLeaders[0].position
                      : ''
                  }}</span>
                </template>
                <template v-else-if="column.field === 'tagName'">
                  <a
                    class="color-primary cur-point mar-r-5"
                    @click="tableClick('toItrServerView', column, scope.row)"
                  >
                    {{ scope.row[column.field] }}
                  </a>
                </template>

                <!-- 服务资源相关 e -->

                <!-- 维保计划相关 s-->
                <template
                  v-else-if="
                    tableKey == 'ITR_MAINTENANCEPLAN_LIST_TABLE' &&
                      column.field === 'name'
                  "
                >
                  <a
                    class="color-primary cur-point mar-r-5"
                    @click="
                      tableClick('toItrMaintenancePlan', column, scope.row)
                    "
                  >
                    {{ scope.row[column.field] }}
                  </a>
                </template>
                <!-- 维保计划相关 e-->

                <!-- BOM相关 s-->
                <template
                  v-else-if="
                    tableKey == 'ITR_BOM_LIST_TABLE' && column.field === 'name'
                  "
                >
                  <a
                    class="color-primary cur-point mar-r-5"
                    @click="
                      tableClick(
                        'toItrBomView',
                        column,
                        scope.row,
                        scope.row.id
                      )
                    "
                  >
                    {{ scope.row[column.field] }}
                  </a>
                </template>
                <!-- BOM相关 e-->
                <!-- 服务资源关联团队相关  s -->
                <template v-else-if="column.field === 'displayName'">
                  <a
                    class="color-primary cur-point mar-r-5 view-user-detail-btn"
                    @click="tableClick('toSecurityUser', column, scope.row)"
                  >
                    {{ scope.row[column.field] }}
                  </a>
                  <i
                    v-if="scope.row.isTeamLeader == 1"
                    class="iconfont icon-people"
                  ></i
                  >主管
                </template>
                <template
                  v-else-if="column.setting && column.setting.tableToView"
                >
                  <div
                    class="link-text"
                    @click="column.setting.tableToView(scope.row)"
                  >
                    {{
                      column.isSystem
                        ? scope.row[column.field]
                        : scope.row.attribute[column.field]
                    }}
                  </div>
                </template>
                <!-- RBRT设备关联设备 s -->
                <template
                  v-else-if="
                    tableKey == 'ITR_PRODUCT_VIEW_LINK_PART_LIST_TABLE' &&
                      column.field === 'endTime'
                  "
                >
                  {{ transProductLinkPartEndTime(scope.row) }}
                </template>
                <template
                  v-else-if="
                    tableKey == 'ITR_PRODUCT_VIEW_LINK_PART_LIST_TABLE' &&
                      column.field === 'state'
                  "
                >
                  {{ transProductLinkPartState(scope.row) }}
                </template>
                <!-- RBRT设备关联设备 e -->
                <template v-else-if="column.field == 'doSome'">
                  <!-- 自定义表单操作内容 -->
                  <div
                    v-if="tableKey == 'ITR_WORK_TREE_DATA_TABLE_INFO_TABLE_IOV'"
                  >
                    <!-- IOV 类目详情表单关联附件 -->
                    <a
                      class="color-primary cur-point mar-r-5"
                      @click="
                        tableClick('editNoSearch', column, scope.row, scope)
                      "
                    >
                      {{$t('common.base.edit')}}
                    </a>
                    <a
                      class="color-danger just-cur-point mar-r-5"
                      @click="
                        tableClick('deleteNoSearch', column, scope.row, scope)
                      "
                    >
                      {{$t('common.base.delete')}}
                    </a>
                  </div>

                  <!-- 设备SN 相关 -->
                  <div
                    v-if="tableKey == 'ITR_PRODUCT_VIEW_LINK_PART_LIST_TABLE'"
                  >
                    <a
                      class="color-primary cur-point mar-r-5"
                      @click="
                        tableClick('editLinkPart', column, scope.row, scope)
                      "
                    >
                      {{$t('common.base.edit')}}
                    </a>
                    <a
                      class="color-danger just-cur-point mar-r-5"
                      @click="
                        tableClick('delLinkPart', column, scope.row, scope)
                      "
                    >
                      {{$t('common.base.delete')}}
                    </a>
                    <a
                      class="color-primary cur-point"
                      @click="
                        tableClick('showLinkPartList', column, scope.row, scope)
                      "
                    >
                      {{$t('common.base.updateRecord')}}
                    </a>
                  </div>
                  <!-- e -->
                  <!-- IOV 类目内容表格编辑s -->
                  <!-- <div v-if="tableKey == 'ITR_WORK_TREE_DATA_TABLE_IOV'">
                  <a
                    type="text"
                    class="color-danger just-cur-point mar-r-5"
                    @click="
                      tableClick(
                        'delProductMenuLinkTable',
                        column,
                        scope.row,
                        scope
                      )
                    "
                  >
                    删除
                  </a>
                </div> -->
                  <!-- IOV 类目内容表格编辑e -->
                  <!--ACE 项目关联服务商相关 || 项目关联点位相关s -->
                  <div
                    v-if="
                      tableKey == 'ITR_PROJECT_LINK_SERVER_LIST' ||
                        tableKey == 'ITR_PROJECT_LINK_POINT_LIST' ||
                        tableKey == 'ITR_PROJECT_LINK_ROUTE_LIST'
                    "
                  >
                    <a
                      class="color-primary cur-point mar-r-5"
                      @click="
                        tableClick(
                          'editLinkServerResources',
                          column,
                          scope.row,
                          scope
                        )
                      "
                    >
                      {{$t('common.base.edit')}}
                    </a>
                    <a
                      class="color-danger just-cur-point mar-r-5"
                      @click="
                        tableClick(
                          'delLinkServerResources',
                          column,
                          scope.row,
                          scope
                        )
                      "
                    >
                      {{$t('common.base.delete')}}
                    </a>
                  </div>
                  <!--ACE 项目关联服务商相关 || 项目关联点位相关 e -->

                  <!-- RBRT 设备类型关联维保计划 s -->
                  <div
                    v-if="
                      tableKey == 'ITR_MAINTENANCEPLAN_LIST_TABLE' ||
                        tableKey ==
                        'ITR_MAINTENANCEPLAN_LINK_CATALOG_LIST_TABLE'
                    "
                  >
                    <a
                      class="color-danger just-cur-point mar-r-5"
                      @click="
                        tableClick(
                          'delLinkMaintenancePlan',
                          column,
                          scope.row,
                          scope
                        )
                      "
                    >
                      {{$t('common.base.delete')}}
                    </a>
                  </div>
                  <!-- RBRT 设备类型关联维保计划 e -->
                  <!-- BOM 启用禁用 s -->
                  <div v-if="tableKey == 'ITR_BOM_LIST_TABLE'">
                    <el-switch
                      v-model="scope.row.enable"
                      :disabled="column.disabled"
                      :active-value="1"
                      :inactive-value="0"
                      @change="tableClick('changeBomState', column, scope.row)"
                    />
                    <span>{{ scope.row.enable ? $t('common.base.enable') : $t('common.base.disable') }}</span>
                  </div>
                  <!-- BOM 启用禁用 e -->
                </template>
                <template v-else-if="column.field === 'roles'">
                  {{
                    scope.row.roles &&
                      scope.row.roles.map((i) => (i && i.name) || '').join('，')
                  }}
                </template>
                <template v-else-if="column.field === 'enabled'">
                  {{ scope.row.enabled == 1 ? $t('common.base.enable') : $t('common.base.disable') }}
                </template>
                <template v-else-if="column.field === 'customer_lmName'">
                  <!-- TO DO 跳转项目详情 -->
                  {{ scope.row.customer && scope.row.customer.lmName }}
                </template>
                <template v-else-if="column.field === 'customer_lmPhone'">
                  {{ scope.row.customer && scope.row.customer.lmPhone }}
                </template>
                <template v-else-if="column.field === 'customer_name'">
                  <a
                    class="color-primary cur-point mar-r-5"
                    @click="
                      tableClick(
                        'toCustomer',
                        column,
                        scope.row,
                        scope.row.customer.id
                      )
                    "
                  >
                    {{ scope.row.customer && scope.row.customer.name }}
                  </a>
                </template>
                <!-- 服务资源关联团队相关 e -->
                <!-- 设备类型相关s -->
                <template v-else-if="column.field === 'catalogName'">
                  <a
                    class="color-primary cur-point mar-r-5"
                    @click="
                      tableClick(
                        'toCatalogLinkInfo',
                        column,
                        scope.row,
                        scope.row.id
                      )
                    "
                  >
                    {{ scope.row[column.field] }}
                  </a>
                </template>
                <template v-else-if="column.field === 'projectName'">
                  <a
                    class="color-primary cur-point mar-r-5"
                    @click="
                      tableClick(
                        'toProjectNameInfo',
                        column,
                        scope.row,
                        scope.row.id
                      )
                    "
                  >
                    {{ scope.row[column.field] }}
                  </a>
                </template>
                <!-- 设备类型相关e -->

                <!-- 项目相关 s -->
                <template v-else-if="column.field === 'customer_name'">
                  <a
                    class="color-primary cur-point mar-r-5"
                    @click="
                      tableClick(
                        'toCustomer',
                        column,
                        scope.row,
                        scope.row.customer.id
                      )
                    "
                  >
                    {{ scope.row.customer && scope.row.customer.name }}
                  </a>
                </template>
                <template v-else-if="column.field === 'pointNo'">
                  <div>
                    {{ `${scope.row.intersectionNo}${scope.row.pointNo}` }}
                  </div>
                </template>
                <!-- 项目相关 e -->

                <template
                  v-else-if="
                    column.field === 'name' &&
                      tableKey !=
                      'ITR_MAINTENANCEPLAN_LINK_SEARCH_LIST_TABLE' &&
                      tableKey !=
                      'ITR_MAINTENANCEPLAN_LINK_CATALOG_LIST_TABLE' &&
                      tableKey != 'ITR_MAINTENANCEPLAN_RECORD_LIST_TABLE'
                  "
                >
                  <sample-tooltip :row="scope.row">
                    <template slot="content" slot-scope="{ isContentTooltip }">
                      <el-tooltip
                        :content="scope.row[column.field]"
                        placement="top-start"
                        :disabled="!isContentTooltip"
                      >
                        <a
                          href=""
                          class="view-detail-btn"
                          @click.stop.prevent="openProductTab(scope.row.id)"
                        >
                          {{ scope.row[column.field] }}
                        </a>
                      </el-tooltip>
                    </template>
                  </sample-tooltip>
                </template>
                <template
                  v-else-if="column.field === 'customer' && scope.row.customer"
                >
                  <a
                    href=""
                    class="view-detail-btn"
                    @click.stop.prevent="
                      createCustomerTab(scope.row.customer.id)
                    "
                  >
                    {{ scope.row.customer.name }}
                  </a>
                </template>
                <template v-else-if="column.field === 'productTemplate'">
                  <a
                    href=""
                    class="view-detail-btn"
                    @click.stop.prevent="
                      createTemplateTab(scope.row.templateId)
                    "
                  >
                    {{ scope.row.templateName }}
                  </a>
                </template>
                <template v-else-if="column.field === 'tags'">
                  {{ scope.row | formatTags }}
                </template>
                <!-- 自定义的选择类型字段显示， 与type 区别-->
                <template v-else-if="column.formType === 'cascader'">
                  {{ scope.row[column.field] | displaySelect }}
                </template>
                <template
                  v-else-if="column.formType === 'select' && !column.isSystem"
                >
                  {{ scope.row.attribute[column.field] | displaySelect }}
                </template>
                <template v-else-if="column.field === 'updateTime'">
                  <template v-if="scope.row.latesetUpdateRecord">
                    <el-tooltip
                      class="item"
                      effect="dark"
                      :content="scope.row.latesetUpdateRecord"
                      placement="top-start"
                    >
                      <!-- <div @mouseover="showLatestUpdateRecord(scope.row)"> -->
                      {{ scope.row.updateTime | formatDate(column) }}
                      <!-- </div> -->
                    </el-tooltip>
                  </template>
                  <template v-else>
                    <!-- <div @mouseover="showLatestUpdateRecord(scope.row)"> -->
                    {{ scope.row.updateTime | formatDate(column) }}
                    <!-- </div> -->
                  </template>
                </template>
                <template v-else-if="column.formType === 'user'">
                  <a
                    class="color-primary cur-point mar-r-5"
                    @click="tableClick('toUser', column, scope.row)"
                    v-if="1 == 2"
                  >
                    {{ getUserName(column, scope.row) }}
                  </a>
                  <span v-else>{{ getUserName(column, scope.row) }}</span>
                </template>
                <template v-else-if="column.formType === 'address'">
                  {{ getAddress(scope.row[column.field]) }}
                </template>
                <template v-else-if="column.formType === 'location'">
                  {{
                    scope.row.attribute[column.field] &&
                      scope.row.attribute[column.field].address
                  }}
                </template>
                <template v-else-if="column.formType == 'related_task'">
                  {{ getRelatedTask(scope.row.attribute[column.field]) }}
                </template>
                <template v-else-if="column.field === 'createUser'">
                  {{ scope.row.createUser && scope.row.createUser.displayName }}
                </template>
                <template v-else-if="column.field === 'createTime'">
                  {{ scope.row.createTime | formatDate(column) }}
                </template>

                <template v-else-if="column.fieldName == 'linkmanName'">
                  {{ scope.row.linkman.name }}
                </template>

                <template v-else-if="column.fieldName == 'phone'">
                  {{ scope.row.linkman.phone }}
                </template>

                <template v-else-if="column.fieldName == 'address'">
                  {{ getAddress(scope.row.address) }}
                </template>

                <template
                  v-else-if="
                    column.label == $t('common.label.buyDate') || column.label == $t('common.label.expiryDate')
                  "
                >
                  {{ scope.row.attribute[column.field] | formatDate2 }}
                </template>

                <template v-else-if="column.formType === 'date'">
                  <div v-if="column.isSystem">
                    {{ scope.row[column.field] | formatDate(column) }}
                  </div>
                  <div v-else>
                    {{ scope.row.attribute[column.field] | formatDate(column) }}
                  </div>
                </template>

                <!-- 移植自设备类型列表并同步更新 s -->

                <template
                  v-else-if="
                    column.fieldName === 'pathName' && !column.banClick
                  "
                >
                  <sample-tooltip
                    :row="scope.row"
                    v-if="scope.row[column.field]"
                  >
                    <template slot="content" slot-scope="{ isContentTooltip }">
                      <a
                        href=""
                        class="view-detail-btn"
                        @click.stop.prevent="
                          openProductMenuTab(scope.row.catalogId)
                        "
                      >
                        {{
                          (scope.row[column.field] &&
                            scope.row[column.field].replace(
                              new RegExp('/', 'g'),
                              ' / '
                          )) ||
                            ''
                        }}
                      </a>
                    </template>
                  </sample-tooltip>
                </template>

                <template v-else-if="column.fieldName === 'productPic'">
                  <div
                    v-if="scope.row.productPic"
                    class="flex-x goods-img-list"
                    style="height:100%"
                  >
                    <template v-for="(item, index) in scope.row.productPic">
                      <!-- <img :key="index"
                           v-if="index <= 4"
                           class="cur-point"
                           :src="
                             item.url
                               ? `${item.url}?x-oss-process=image/resize,m_fill,h_32,w_32`
                               : defaultImg
                           "
                           @click.stop="previewImg(item.url)" /> -->
                      <img
                        :key="index"
                        v-if="index <= 4"
                        class="cur-point size-32"
                        :src="item.url ? `${item.url}` : defaultImg"
                        @click.stop="previewImg(item.url)"
                      />
                    </template>
                    <div>
                      {{
                        scope.row[column.field].length > 5
                          ? `+${scope.row[column.field].length - 5}`
                          : ''
                      }}
                    </div>
                  </div>
                </template>

                <template v-else-if="column.fieldName === 'productVideo'">
                  <template v-if="scope.row.productVideo">
                    <sample-tooltip :row="scope.row">
                      <template
                        slot="content"
                        slot-scope="{ isContentTooltip }"
                      >
                        <a
                          href=""
                          class="view-detail-btn"
                          @click.stop.prevent="
                            previewVideo(scope.row.productVideo[0].url)
                          "
                        >
                          {{
                            scope.row.productVideo[0] &&
                              scope.row.productVideo[0].filename
                          }}
                        </a>
                      </template>
                    </sample-tooltip>
                  </template>
                </template>

                <!-- 移植自设备类型列表并同步更新 e -->

                <template v-else-if="!column.isSystem">
                  <div>{{ scope.row.attribute[column.field] }}</div>
                </template>

                <template v-else>
                  {{ scope.row[column.field] }}
                </template>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
    </div>

    <div class="table-footer">
      <i18n path="common.base.table.totalCount">
        <span place="count" class="level-padding">{{totalItems}}</span>
      </i18n>
      <template v-if="tableSetting.tableSelect && tableSetting.tableSelect.length>0">
        <i18n path="common.base.table.selectedNth">
          <span
            place="count"
            class="product-selected-count"
            @click="multipleSelectionPanelShow = true"
          >{{ multipleSelection.length }}</span>
        </i18n>
        <span 
          class="product-selected-count"
          v-show="multipleSelection.length"
          @click="toggleSelection()"
        >{{$t('common.base.clear')}}</span>
      </template>
      <el-pagination
        v-if="tableSetting.needPageSize"
        class="product-table-pagination"
        background
        @current-change="jump"
        @size-change="handleSizeChange"
        :page-sizes="defaultTableData.defaultPageSizes"
        :page-size="page.pageSize"
        :current-page="page.pageNum"
        layout="prev, pager, next, sizes, jumper"
        :total="page.total"
      >
      </el-pagination>
    </div>

    <!-- 已选列表 s-->
    <base-panel
      class="product-panel"
      :show.sync="multipleSelectionPanelShow"
      width="420px"
    >
      <h3 slot="title">
        <span>已选中({{ multipleSelection.length }})</span>
        <i
          v-if="multipleSelection.length"
          class="iconfont icon-qingkongshanchu product-panel-btn"
          @click="toggleSelection()"
          :title="$t('common.base.tip.clearChoseDataTip')"
          data-placement="right"
          v-tooltip
        ></i>
      </h3>

      <div class="product-selected-panel">
        <div class="product-selected-tip" v-if="!multipleSelection.length">
          <img :src="noDataImage" />
          <p>{{$t('common.base.tip.noSelectedDataFromList')}}</p>
        </div>
        <template v-else>
          <div class="product-selected-list">
            <div class="product-selected-row product-selected-head">
              <span class="product-selected-name">{{ moduleKey }}</span>
            </div>
            <draggable
              tag="div"
              :list="multipleSelection"
              :group="{ name: 'g1' }"
              handle=".handle"
            >
              <div
                class="product-selected-row handle"
                v-for="(c, index) in multipleSelection"
                :key="index"
              >
                <span class="product-selected-sn">{{
                  tableSetting.tableSelectShowKey
                    ? c[tableSetting.tableSelectShowKey]
                    : c.id
                }}</span>
                <button
                  type="button"
                  class="product-selected-delete"
                  @click="removeFromSelection(c)"
                >
                  <i class="iconfont icon-fe-close"></i>
                </button>
              </div>
            </draggable>
          </div>
        </template>
      </div>
    </base-panel>
    <!-- 已选列表 e-->

    <!-- 导入 s -->
    <base-import
      title="导入"
      ref="importProductModal"
      @success="search"
      :is-import-now="tableSetting.isImportNow"
      :action="tableSetting.importUrl"
    >
      <div slot="tip">
        <div class="base-import-warn">
          <i18n path="common.base.importModal.downloadTemplateTip" tag="p">
            <a place="link" :href="tableSetting.importTempUrl">{{$t('common.base.importModal.importTemplate')}}</a>
          </i18n>
          <!--<p>导入设备前，请确保设备所属客户已存在。您可以 <a href="/customer/import/getAllCustomerId">点这里</a>导出包含所有已存在客户的模板</p>-->
        </div>
      </div>
    </base-import>
    <!-- 导入 e -->

    <!-- start 导出s -->
    <base-export-group
      ref="exportPanel"
      :alert="exportAlert"
      :columns="exportColumns"
      :build-params="buildExportParams"
      :group="true"
      :validate="checkExportCount"
      :needchoose-break="false"
      method="post"
      :action="tableSetting.exportUrl"
      :export-type="'free'"
      :key-id="`${tableKey}-list`"
      :export-skip-select="tableSetting.exportSkipSelect"
      :is-export-now="tableSetting.isExportNow"
    />
    <!-- end 导出e -->

    <!-- 选择列 s -->
    <biz-select-column
      ref="advanced"
      :storage-key="tableKey"
      @save="saveColumnStatus"
    />
    <!-- 选择列 e -->

    <!-- 高级搜索 s -->
    <search-panel
      :config="{
        fields: searchFields,
      }"
      :table-key="tableKey"
      :search-modal-storage="storageKeySearchModal"
      :search-panel-storage="storageKeySearchPanel"
      ref="searchPanel"
    >
      <div class="advanced-search-btn-group" slot="footer">
        <base-button type="ghost" @event="resetParams">{{$t('common.base.reset')}}</base-button>
        <base-button type="primary" @event="powerfulSearch" native-type="submit"
        >{{$t('common.base.search')}}</base-button
        >
      </div>
    </search-panel>
    <!-- 高级搜素 e -->
  </div>
</template>

<script>
import { t } from '@src/locales'
import { getOssUrl } from '@src/util/assets'
const noDataImage = getOssUrl('/no_data.png')
import _ from 'lodash';
import Page from '@model/Page';
import draggable from 'vuedraggable';
import { formatDate } from 'pub-bbx-utils';
import { getRootWindow } from '@src/util/dom';
import { storageGet, storageSet } from '@src/util/storageV2';
import {
  storageEnum,
  moduleEnum,
} from '@src/component/compomentV2/BaseTable/storage.js';
import { defaultTableData } from '@src/util/table'
import SearchPanel from '@src/component/compomentV2/BaseTable/compoment/SearchPanelForBaseTable.vue';
import { safeNewDate } from '@src/util/time';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { formatAddress } from 'pub-bbx-utils';
import { fmtDist } from '@src/util/addressUtil';
/**
 * @des 基本表单集成的功能设置
 * @param {Boolean} needSearch 搜索模块
 * @param {Boolean} needSelect 选择列模块
 * @param {Boolean} needExport 导出模块
 * @param {Boolean} needExportAll 导出全部模块
 * @param {Boolean} needImport 导入模块
 * @param {Boolean} needAdvancedSearch 高级搜索模块
 * @param {Boolean} needPageSize 分页模块
 * @param {Boolean} exportSkipSelect 是否跳过导出时选择列操作
 * @param {Boolean} tableSelect 是否需要表单选择功能
 * @param {Boolean} fastExport 针对后端快速提供导出功能
 * @param {String} searchPlaceholder 搜索占位内容
 * @param {Object} searchParams 搜索自带参数
 * @param {Boolean} isImportNow 导入之后是否立即调用钩子函数 一般用于不在任务列表的导入
 * @param {Boolean} isExportNow 导出之后是否立即调用钩子函数 一般用于不在任务列表的导出
 * @param {String} addFncText 新建按钮的内容
 * @param {String} delFncText 删除按钮的内容
 * @param {String} delTipText 删除提示的内容
 * @param {String} delTipNullText 删除未选择提示的内容
 * @param {Boolean} needMountedSearch 需要加载完成调用Search
 * @param {Promise} delFncParams  删除参数需要转换的格式
 * @param {Promise} delFnc 删除需要调用的api
 * @param {Function} addFnc 新建需要触发的函数
 * @param {Boolean} needStroage 需要本地缓存用户的行为习惯
 * @param {Boolean} haveTreeTable 是否是树形表单
 * @param {Number} selectedLimit 限制多选的个数为-1则不限制
 * @param {Boolean} oldSearchList 请求参数是老的无code返回体
 * @param {String} keywordValue keyword的值
 * @param {String} exportKey 导出选择字段的key
 * @param {String} exportIdKey 导出的id的key
 * @param {String} tableSelectShowKey 选择的主key
 * @author dove
 */
const tableSettingTemp = {
  needSearch: false,
  needSelect: false,
  needExport: false,
  needExportAll: false,
  needImport: false,
  needPageSize: true,
  needAdvancedSearch: false,
  needMountedSearch: true,
  tableSelect: false,
  fastExport: null,
  exportTitle: '测试标题',
  exportSkipSelect: false,
  searchPlaceholder: '请输入',
  searchParams: null,
  isImportNow: false,
  isExportNow: false,
  addFncText: '新建',
  delFncText: '删除',
  needStroage: true,
  delTipText: '',
  delTipNullText: '',
  haveTreeTable: false,
  selectedLimit: -1,
  oldSearchList: false,
  keywordValue: 'keyword',
  exportKey: 'productExport',
  exportIdKey: 'data',
};
export default {
  name: 'base-table-for-usual',
  // 使用该参数必须保证有全局的initData
  inject: ['initData'],
  props: {
    tableKey: {
      type: String,
      default: 'TEST_TABLE',
    },
    tableColumns: {
      type: Array,
      default: () => [],
    },
    tableSettingProp: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  components: {
    [SearchPanel.name]: SearchPanel,
    draggable,
  },
  data() {
    return {
      defaultTableData,
      noDataImage,
      page: new Page(), // 用户列表
      backPageList: [],
      searchModel: {
        keyword: '',
        pageSize: 10,
        pageNum: 1,
        orderDetail: {},
        moreConditions: {
          conditions: [],
        },
      },
      multipleSelection: [],
      columns: [],
      multipleSelectionPanelShow: false,
      loading: false,
    };
  },
  filters: {
    formatTags({ customer }) {
      if (!customer) return '';
      if (!customer.tags || !customer.tags.length) return '';
      return customer.tags.map((t) => t.tagName).join(' ');
    },
    formatDate(val, column) {
      if (!val) return '';
      if (
        typeof val == 'string'
        && (val.indexOf(':') > -1
          || val.indexOf('-') > -1
          || val.indexOf('/') > -1)
      )
        return val;
      if (`${val}`.indexOf('-') > -1)
        val = val.replace(new RegExp('-', 'g'), '/');
      let dateStr = 'YYYY-MM-DD HH:mm:ss';
      if (
        column
        && column.hasOwnProperty('setting')
        && column.setting.hasOwnProperty('dateType')
      )
        dateStr = column.setting.dateType;
      val = safeNewDate(val);
      return formatDate(val, dateStr);
    },
    formatDate2(val) {
      if (!val) return '';
      return formatDate(val, 'YYYY-MM-DD');
    },
    displaySelect(value) {
      if (!value) return null;
      if (value && typeof value === 'string') {
        return value;
      }
      if (Array.isArray(value) && value.length) {
        return value.join('，');
      }
      return null;
    },
    teamLeadersFilter(val) {
      try {
        let arr = [];
        arr = val.map((item) => `${item.displayName || ''}`);
        return arr.join(',');
      } catch (error) {
        console.warn(error, 'error try catch');
        return '';
      }
    },
    tagPlaceListFilter(val) {
      try {
        let arr = [];
        arr = val.map(
          (item) => fmtDist(item)
        );
        return arr.join(',');
      } catch (error) {
        console.warn(error, 'error try catch');
        return '';
      }
    },
  },
  computed: {
    tableSetting() {
      return { ...tableSettingTemp, ...this.tableSettingProp };
    },
    tableFields() {
      let fixedFields = this.tableColumns;
      return fixedFields;
    },
    /**
     * @des 高级搜索所需表单
     */
    searchFields() {
      let arr_ = this.tableFields;
      return arr_;
    },
    storageKey() {
      return storageEnum[this.tableKey] || 'test_dev';
    },
    moduleKey() {
      return moduleEnum[this.tableKey] || 'test_dev';
    },
    selectedIds() {
      return this.multipleSelection.map((p) => p.id);
    },
    tenantType() {
      try {
        return getRootWindow(window)
          .getItrTenantType()
          .get();
      } catch (error) {
        console.warn(error, 'error try catch');
        return '';
      }
    },
    exportColumns() {
      let arr = [...this.columns]
        .filter((item) => item.formType !== 'doSome')
        .map((field) => {
          if (
            ['customer', 'productTemplate', 'remindCount'].some(
              (key) => key === field.fieldName
            )
            || field.formType === 'info'
          ) {
            field.export = false;
          } else {
            field.export = true;
          }
          return field;
        });

      let arr_ = [
        {
          label: this.tableSetting.exportTitle,
          value: 'productExport',
          columns: arr,
        },
      ];
      return arr_;
    },
    storageKeySearchModal() {
      return `${this.storageKey}_searchModal`;
    },
    storageKeySearchPanel() {
      return `${this.storageKey}_searchPanel`;
    },
  },
  created() {},
  mounted() {
    this.resetPage(true);
  },
  methods: {
    resetPage(isMounted) {
      this.buildColumns();
      this.revertStorage();
      if (isMounted && this.tableSetting.needMountedSearch) {
        this.search();
      }
    },
    // 搜索
    search() {
      let params = this.buildParams();
      if (this.tableSetting.searchParams) {
        params = { ...params, ...this.tableSetting.searchParams };
      }
      // 不分页参数
      if (!this.tableSetting.needPageSize) params.pageNum = 0;
      // 针对IOV新建
      if (params.hasOwnProperty('catalogId') && !params.catalogId) return;
      this.loading = true;
      return this.tableSetting
        .search(params)
        .then((res) => {
          if (this.tableSetting.oldSearchList) {
            this.$set(this.page, 'list', res.list);
            this.backPageList = res.list;
            this.page['total'] = res.total;
            this.page['pageNum'] = res.pageNum;
            this.matchSelected();
          } else if (res.code == 0 || res.status == 0) {
            let res_;
            if (res.hasOwnProperty('data')) res_ = res.data;
            if (res.hasOwnProperty('result')) res_ = res.result;
            if (res_.hasOwnProperty('content')) {
              // 兼容es list的返回体结构
              this.$set(this.page, 'list', res_.content);
              this.backPageList = res_.content;
              this.page['total'] = res_.totalElements;
            } else if (res_.hasOwnProperty('list')) {
              this.$set(this.page, 'list', res_.list);
              this.backPageList = res_.list;
              this.page['total'] = res_.total;
            }

            this.page['pageNum'] = res_.pageNum;
            this.matchSelected();
          } else {
            throw res;
          }
        })
        .catch((err) => {
          console.log(err, 'err');
          this.$notify.error({
            title: t('common.base.toast'),
            message: err.message,
            duration: 2000,
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /**
     * @description 表头更改
     */
    headerDragend(newWidth, oldWidth, column, event) {
      let data = this.columns
        .map((item) => {
          if (item.fieldName === column.property) {
            item.width = column.width;
          }
          return item;
        })
        .map((item) => {
          return {
            field: item.field,
            show: item.show,
            width: item.width,
          };
        });
      this.modifyColumnStatus({ type: 'column', data });
    },
    jump(pageNum) {
      this.searchModel.pageNum = pageNum;
      this.search();
    },
    handleSizeChange(pageSize) {
      this.saveDataToStorage('pageSize', pageSize);
      this.searchModel.pageSize = pageSize;
      this.searchModel.pageNum = 1;
      this.search();
    },
    buildSortFields(originFields = [], fieldsMap = {}) {
      let fields = [];
      let unsortedFields = [];

      originFields.forEach((originField) => {
        let { fieldName } = originField;
        let field = fieldsMap[fieldName];

        if (field) {
          let { index } = field;
          fields[index] = originField;
        } else {
          unsortedFields.push(originField);
        }
      });

      return fields.concat(unsortedFields);
    },
    buildColumns() {
      let columnStatus = [];
      try {
        const localStorageData = this.getLocalStorageData();
        columnStatus = localStorageData.columnStatus
          && localStorageData.columnStatus[this.storageKey];
        columnStatus = columnStatus || [];
      } catch (error) {
        console.warn(error, 'error try catch');
      }

      // let localColumns = columnStatus
      //   .map((i) => (typeof i == 'string' ? { field: i, show: true } : i))
      //   .reduce((acc, col) => (acc[col.field] = col) && acc, {});
      let arr_ = [];

      let localColumns = columnStatus
        .filter((item) => item.show)
        .map((i) => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col, currentIndex) => {
          acc[col.field] = {
            field: col,
            index: currentIndex,
          };
          return acc;
        }, {});
      let fields = this.tableFields;
      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        fields = this.buildSortFields(fields, localColumns);
      }

      arr_ = fields
        .filter(
          (f) =>
            f.formType !== 'attachment'
            && f.formType !== 'separator'
            && f.formType !== 'info'
            && f.formType !== 'autograph'
        )
        .map((field) => {
          let sortable = false;
          let minWidth = null;

          if (
            ['date', 'datetime', 'number'].indexOf(field.formType) >= 0
            && field.isSystem
          ) {
            sortable = 'custom';
            minWidth = 100;
            if (field.hasOwnProperty('sort') && !field.sort) sortable = false;
          }

          if (field.fieldName === 'type' && field.tableName == 'product') {
            sortable = 'custom';
          }

          if (field.displayName.length > 4) {
            minWidth = field.displayName.length * 20;
          }

          if (sortable && field.displayName.length >= 4) {
            minWidth = 125;
          }

          if (
            field.formType === 'datetime'
            || field.fieldName === 'updateTime'
            || field.fieldName === 'createTime'
          ) {
            minWidth = 150;
          }
          if (field.minWidth) {
            minWidth = field.minWidth;
          }

          return {
            ...field,
            label: field.displayName,
            field: field.fieldName,
            formType: field.formType,
            minWidth: typeof minWidth == 'number' ? minWidth : `${minWidth}px`,
            sortable,
            isSystem: field.isSystem,
            showKey: field.showKey || '',
          };
        })
        .map((col) => {
          let show = col.show === true;
          let width = col.width;
          let localField = (localColumns[col.field] && localColumns[col.field].field) || null;

          if (null != localField) {
            width = typeof localField.width == 'number'
              ? `${localField.width}px`
              : `${localField.width}`.indexOf('px')
                ? localField.width
                : '';
            show = localField.show !== false;
          }

          col.show = col.isSystem ? true : show;
          if (col.formType == 'related_catalog') {
            col.show = true;
          }
          col.width = width;
          col.type = 'column';

          return col;
        });
      this.$set(this, 'columns', arr_);
    },
    getLocalStorageData() {
      try {
        const dataStr = storageGet(this.storageKey);
        return JSON.parse(dataStr);
      } catch (error) {
        return {};
      }
    },
    saveDataToStorage(key, value) {
      if (!this.tableSetting.needStroage) return;
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet(this.storageKey, JSON.stringify(data));
    },
    createCustomerTab(productId) {
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `customer_view_${productId}`,
      //   title: '客户信息',
      //   close: true,
      //   url: `/customer/view/${productId}?noHistory=1`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: productId,
        params: 'noHistory=1',
        fromId
      })
    },
    revertStorage() {
      const { pageSize } = this.getLocalStorageData();
      if (pageSize) {
        this.searchModel.pageSize = pageSize;
      }
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    modifyColumnStatus(event) {
      let columns = event.data || [],
        colMap = columns.reduce(
          (acc, col) => (acc[col.field] = col) && acc,
          {}
        );
      this.columns.forEach((col) => {
        let newCol = colMap[col.field];
        if (null != newCol) {
          this.$set(col, 'show', newCol.show);
          this.$set(col, 'width', newCol.width);
        }
      });

      this.saveColumnStatusToStorage();
      this.$message.success(this.$t('common.base.saveSuccess'));
    },
    saveColumnStatusToStorage() {
      const localStorageData = this.getLocalStorageData();
      let columnsStatus = null;

      // 判断是否存储选择列
      const columnsList = this.columns.map((c) => ({
        field: c.field,
        show: c.show,
        width: c.width,
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus[`${this.storageKey}`] = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = {
          [`${this.storageKey}`]: columnsList,
        };
      }

      this.saveDataToStorage('columnStatus', columnsStatus);
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    saveColumnStatus(event) {
      let columns = event.data || [];

      this.columns = [];

      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.saveColumnStatusToStorage();
      });
    },
    handleSelectionAll(selection) {
      // 有树级结构的情况需要对选择项处理 TO DO 取消当前表格的全部勾选
      // try {
      //   if (this.tableSetting.haveTreeTable) {
      //     return this.handleSelection(this.filterTreeTableSelect(selection));
      //   }
      // } catch (error) {
      //   console.warn(error, 'error try catch');
      // }
      this.handleSelection(selection);
    },

    handleSelection(selection, row) {
      let tv = this.selectionCompute(selection);

      // let original = tv.filter((ms) =>{
      //   this.page.list.some((cs) => {
      //     if(cs.id === ms.id) return true;
      //     let boolean = this.tableSetting.haveTreeTable ? false : true;
      //     if (cs.hasOwnProperty('children') && cs.children.length)
      //       boolean = this.findHaveChild(cs.children, ms.id);
      //     return boolean
      //   });
      // });

      // let unSelected = this.page.list.filter((c) =>
      //   original.every((oc) => oc.id !== c.id)
      // );
      let unSelected = [];
      let unSelected_ = [];
      unSelected_ = selection.filter((item) => {
        return !this.multipleSelection.find((item_) => item_.id == item.id);
      });
      if (unSelected_.length)
        unSelected_.map((item) => {
          let res_ = false;
          res_ = this.findHaveChild(this.page.list, item.id);
          if (res_) unSelected.push(res_);
        });

      if (
        tv.length > this.tableSetting.selectedLimit
        && this.tableSetting.selectedLimit > 0
      ) {
        this.$nextTick(() => {
          unSelected.length > 0 && this.multipleSelection.length
            ? unSelected.forEach((row) => {
              this.$refs.multipleTable.toggleRowSelection(row, false);
            })
            : this.$refs.multipleTable.clearSelection();
        });
        return this.$platform.alert(t('common.base.tip.maxDataCanChooseTips'));
      }
      this.multipleSelection = tv;

      this.$refs.baseSelectionBar?.openTooltip();
    },
    // 计算已选择
    selectionCompute(selection) {
      let tv = [];
      tv = this.multipleSelection.filter((ms) => {
        let boolean = !this.tableSetting.haveTreeTable;
        if (ms.hasOwnProperty('children') && ms.children && ms.children.length)
          boolean = this.findHaveChild(ms.children, ms.id);
        return boolean && this.page.list.every((c) => c.id !== ms.id);
      });
      tv = _.uniqWith([...tv, ...selection], _.isEqual);

      return tv;
    },
    /**
     * @des 遍历寻找数组内符合的item
     * TO DO 查询多个
     */
    findHaveChild(arr, id, bool = false) {
      if (arr && arr.length) {
        for (let index = 0; index < arr.length; index++) {
          const element = arr[index];
          if (bool) {
            break;
          }
          if (element.id == id) {
            bool = element;
            break;
          }
          if (
            element.hasOwnProperty('children')
            && element.children
            && element.children.length
          ) {
            bool = this.findHaveChild(element.children, id, bool);
          }
        }
        return bool;
      }
    },
    /**
     * @des 遍历寻找数组内符合的item
     */
    findHaveChildArr(arr, ids, bool = []) {
      if (arr && arr.length) {
        for (let index = 0; index < arr.length; index++) {
          let element = arr[index];
          if (ids.find((item_) => item_.id == element.id)) {
            bool = [...bool, element];
          }
          if (bool && bool.length == ids.length) {
            break;
          }
          if (
            element.hasOwnProperty('children')
            && element.children
            && element.children.length
          ) {
            bool = this.findHaveChildArr(element.children, ids, bool);
          } else {
            continue;
          }
        }
      }
      return bool;
    },
    /**
     * @des 处理树结构的选择问题
     */
    filterTreeTableSelect(arr, res_ = []) {
      let arr_ = arr;
      arr_.map((item) => {
        res_.push(item);
        this.toggleRowSelection(item, true);
        if (
          item.hasOwnProperty('children')
          && item.children
          && item.children.length
        ) {
          res_ = this.filterTreeTableSelect(item.children, res_);
        }
      });
      return res_;
      // if (
      //   nowChoose.hasOwnProperty('children')
      //   && nowChoose.children.length
      // ) {
      //   let chooseArr_ = [...arr_];
      //   if (!check) {
      //     chooseArr_ = chooseArr_.filter((item_) => item_.id != nowChoose.id);
      //   }
      //   nowChoose.children.map((item) => {
      //     this.$refs.multipleTable.toggleRowSelection(item, check);
      //     if (check) {
      //       chooseArr_ = [...arr_, item];
      //     } else {
      //       chooseArr_ = chooseArr_.filter((item_) => item_.id != item.id);
      //     }
      //     console.log(chooseArr_, 'chooseArr_');
      //     this.handleSelection(chooseArr_, item);
      //   });
      // }
    },
    /**
     * @des 子树里不是全选需要取消父级的选择
     */
    toggleRowSelection(item) {
      this.$refs.multipleTable.toggleRowSelection(item, true);
    },
    sortChange(option) {
      try {
        const { prop, order } = option;
        if (!order) {
          this.searchModel.orderDetail = {};
          return this.search();
        }
        const sortedField = this.tableFields.filter((sf) => sf.fieldName === prop)[0] || {};

        let isSystem = 0;

        if (prop === 'createTime' || prop === 'updateTime') {
          isSystem = 1;
        } else {
          isSystem = sortedField.isSystem;
        }

        let sortModel = {
          isSystem,
          sequence: order === 'ascending' ? 'ASC' : 'DESC',
          column: isSystem ? `${prop}` : prop,
        };

        if (
          prop === 'createTime'
          || prop === 'updateTime'
          || sortedField.formType === 'date'
          || sortedField.formType === 'datetime'
        ) {
          sortModel.type = 'date';
        } else {
          sortModel.type = sortedField.formType;
        }

        this.searchModel.orderDetail = sortModel;

        this.search();
      } catch (e) {
        console.error('e', e);
      }
    },

    toggleSelection(rows, type = true) {
      let isNotOnCurrentPage = false;
      let item = undefined;

      if (rows) {
        // for (let i = 0; i < rows.length; i++) {
        //   row = rows[i];
        //   isNotOnCurrentPage = this.page.list.every((item) => {
        //     return item.id !== row.id;
        //   });
        //   if (isNotOnCurrentPage) return;
        // }
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row, type);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
        this.multipleSelection = [];
      }
    },
    removeFromSelection(c) {
      if (!c || !c.id) return;

      this.multipleSelection = this.multipleSelection.filter(
        (ms) => ms.id !== c.id
      );
      this.multipleSelection.length < 1
        ? this.toggleSelection()
        : this.toggleSelection([c], false);
    },

    buildParams() {
      const sm = Object.assign({}, this.searchModel);
      let params = {
        keyword: sm.keyword,
        pageSize: sm.pageSize,
        pageNum: sm.pageNum,
      };
      params[this.tableSetting.keywordValue] = sm.keyword;

      if (Object.keys(sm.orderDetail || {}).length) {
        params.orderDetail = sm.orderDetail;
      }

      if (
        Object.keys(sm.moreConditions).length > 1
        || sm.moreConditions.conditions.length
      ) {
        params = {
          ...params,
          ...sm.moreConditions,
        };
      }

      return params;
    },
    /**
     * @description 导出提示
     */
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message);
    },
    /** 检测导出条数 */
    checkExportCount(ids, max) {
      let exportAll = !ids || !ids.length;
      return exportAll && this.page.total > max
        ? t('common.base.tip.exportLimit', { max })
        : null;
    },
    /**
     * @description 构建导出参数
     * @return {Object} 导出参数
     */
    buildExportParams(checkedMap, ids, exportOneRow) {
      const { productExport } = checkedMap;
      const Params = Object.assign({}, this.params);
      const rootWindow = getRootWindow(window);
      const { loginUser } = this.initData;

      let exportAll = !ids || !ids.length;
      const all = exportAll
        ? {
          ...this.buildParams(),
          ids: this.selectedIds,
          // tagIds: loginUser.tagIds,
          tenantId: JSON.parse(rootWindow._init).user.tenantId,
        }
        : {
          ids: this.selectedIds,
          // tagIds: loginUser.tagIds,
          tenantId: JSON.parse(rootWindow._init).user.tenantId,
        };

      let exportSearchModel = {};
      let params = {
        exportSearchModel: JSON.stringify({
          ...all,
          ...{
            exportTotal: exportAll ? this.page.total : this.selectedIds.length,
          },
        }),
      };
      /** ********************* *********************/
      // 信息
      let export_product = this.exportData(0, productExport);

      params['exportOneRow'] = exportOneRow;
      params[this.tableSetting.exportIdKey] = exportAll
        ? ''
        : this.selectedIds.join(',');

      params[this.tableSetting.exportKey] = export_product.join(',');

      return params;
    },
    panelSearchAdvancedToggle() {
      this.$refs.searchPanel.open();
      this.$nextTick(() => {
        let forms = document.getElementsByClassName('advanced-search-form');
        for (let i = 0; i < forms.length; i++) {
          let form = forms[i];
          form.setAttribute('novalidate', true);
        }
      });
    },
    openDialog(action) {
      try {
        const fnEnum = {
          // 批量编辑
          edit: () => {
            this.$refs.batchEditingDialog.open();
          },
          // 导入
          importProduct: () => {
            this.$refs.importProductModal.open();
          },
          // 导出
          update: () => {
            this.$refs.batchUpdateDialog.openBatchUpdateCustomerDialog();
          },
          // 选择列
          select: () => {
            let arr_ = _.cloneDeep(this.columns);
            this.$refs.advanced.open(arr_);
          },
        };
        fnEnum[action]();
      } catch (error) {
        console.warn(error, 'error try catch');
      }
    },
    exportFn(exportAll) {
      if (this.tableSetting.fastExport) {
        // 快速导出
        window.location.href = this.tableSetting.fastExport;
        return;
      }
      let ids = [];
      let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')}${this.tableSetting
        .exportTitle || ''}.xlsx`;
      if (!exportAll) {
        if (!this.multipleSelection.length)
          return this.$platform.alert(t('common.base.tip.exportNoChoice'));
        ids = this.selectedIds;
      }
      this.$refs.exportPanel.open(ids, fileName);
    },
    resetParams() {
      this.searchModel = {
        keyword: '',
        pageNum: 1,
        pageSize: this.page.pageSize,
        orderDetail: {},
        moreConditions: {
          conditions: [],
        },
      };
      // this.multipleSelection = [];
      this.backPageList = [];
      this.$refs.searchPanel.resetParams();
      this.search();
    },
    resetTable() {
      this.searchModel = {
        keyword: '',
        pageNum: 1,
        pageSize: this.page.pageSize,
        orderDetail: {},
        moreConditions: {
          conditions: [],
        },
      };

      this.$refs.searchPanel.resetParams();
      this.$set(this, 'multipleSelection', []);
      this.$set(this, 'backPageList', []);
      this.$set(this, 'page', new Page());
    },
    powerfulSearch() {
      this.searchModel.pageNum = 1;
      this.searchModel.moreConditions = this.$refs.searchPanel.buildParams();

      this.search();
    },
    // 匹配选中的列
    // TO DO 层级列表需要深层遍历 到子元素
    matchSelected() {
      if (!this.multipleSelection.length) return;

      // const selected = this.page.list.filter((c) => {
      //   if (this.multipleSelection.some((sc) => sc.id === c.id)) {
      //     this.multipleSelection = this.multipleSelection.filter(
      //       (sc) => sc.id !== c.id
      //     );
      //     this.multipleSelection.push(c);
      //     return c;
      //   }
      // }) || [];
      // const selected = this.multipleSelection.map((item) => {
      //   if (this.page.list.some((item_) => item_.id == item.id)) {
      //     return this.page.list.find((items) => items.id == item.id);
      //   }
      //   let boolean = !this.tableSetting.haveTreeTable;
      //   item = this.page.list.map((item_) => {
      //     if (
      //       item_.hasOwnProperty('children')
      //         && item_.children
      //         && item_.children.length
      //     )
      //       boolean = this.findHaveChild(item_.children, item.id);
      //     return boolean;
      //   });
      //   return item;
      // }) || [];
      let selected = [];
      if (this.page.list && this.page.list.length) {
        let boolean = false;
        boolean = this.findHaveChildArr(this.page.list, this.multipleSelection);
        if (boolean) selected = [...selected, ...boolean];
      }
      selected = selected && selected.length ? selected : [];

      this.$nextTick(() => {
        this.toggleSelection(selected);
      });
    },
    formatCustomizeAddress(ad) {
      if (null == ad) return '';
      return formatAddress(ad);
    },
    getAddress(field) {
      return formatCustomizeAddress(field);
    },
    // 处理人员显示
    getUserName(field, scope) {
      try {
        let value = field.isSystem
          ? scope[field.field]
          : scope.attribute[field.field];
        // 多选
        if (Array.isArray(value)) {
          return value
            .map((i) => i.displayName || i.name || i[field.showKey])
            .join(',');
        }

        let user = value || {};
        return user.displayName || user.name || user[field.showKey];
      } catch (error) {
        return '';
      }
    },
    /**
     * 导出数据
     */
    exportData(number, list = []) {
      const export_list = this.exportColumns;
      if (!list.length) return;
      if (number === 3) {
        let cardField = [];
        export_list
          .filter((item, index) => {
            return index > 2;
          })
          .forEach((v) => {
            v.columns.forEach((item) => {
              cardField.push(item);
            });
          });
        return cardField
          .map((v) => {
            let bool = list.some((item) => {
              if (v.exportAlias) {
                return v.exportAlias === item;
              }
              return v.fieldName === item;
            });
            if (bool) {
              return v.exportAlias ? v.exportAlias : v.fieldName;
            }
          })
          .filter((item) => {
            return item;
          });
      }

      return export_list[number].columns
        .map((v) => {
          let bool = list.some((item) => {
            if (v.exportAlias) {
              return v.exportAlias === item;
            }
            return v.fieldName === item;
          });
          if (bool) {
            return v.exportAlias ? v.exportAlias : v.fieldName;
          }
        })
        .filter((item) => {
          return item;
        });
    },
    tableClick(type, columns, scope, param) {
      const typeEnum = {
        toUser: () => {
          console.log('去人员详情');
        },
        toItrServerView: () => {
          // this.$platform.openTab({
          //   id: `itrServerResources_view_${scope.id}`,
          //   title: '服务资源详情',
          //   url: `/itrServerResources/view?id=${scope.id}`,
          //   reload: true,
          // });
          openAccurateTab({
            type: PageRoutesTypeEnum.PageItrServerResources,
            key: scope.id,
            params: `id=${scope.id}`,
            reload: true,
          })
        },
        toSecurityUser: () => {
          // this.$platform.openTab({
          //   id: `tab_department_view_${scope.userId}`,
          //   title: '成员详情',
          //   close: true,
          //   reload: true,
          //   url: `/security/user/view/${scope.userId}`,
          // });
          openAccurateTab({
            type: PageRoutesTypeEnum.PageSecurityUserView,
            key: scope.userId,
            reload: true,
          })
        },
        toCustomer: () => {
          if (!param) return console.log('客户id为空');
          // this.$platform.openTab({
          //   id: `customer_view_${param}`,
          //   title: '成员详情',
          //   close: true,
          //   reload: true,
          //   url: `/customer/view/${param}`,
          // });
          openAccurateTab({
            type: PageRoutesTypeEnum.PageCustomerView,
            key: param,
            reload: true,
          })
        },
        toProjectNameInfo: () => {
          if (!param) return console.log('项目id为空');
          // this.$platform.openTab({
          //   id: `itrProject_view_${param}`,
          //   title: '项目详情',
          //   close: true,
          //   reload: true,
          //   url: `/itrProject/view?id=${param}`,
          // });

          openAccurateTab({
            type: PageRoutesTypeEnum.PageFeItrProjectView,
            key: param,
            params: `id=${param}`,
            reload: true,
          })
        },
        toCatalogLinkInfo: () => {
          this.$emit('watchTableFnc', {
            type: 'toCatalogLinkInfo',
            params: { id: param, parentId: scope.parentId },
          });
        },
        toItrMaintenancePlan: () => {
          if (!scope || !scope.id) return console.log('维保计划id为空');
          // this.$platform.openTab({
          //   id: `itrMaintenancePlan_view_${scope.id}`,
          //   title: '编辑维保计划',
          //   close: true,
          //   reload: true,
          //   url: `/itrMaintenancePlan/edit?id=${scope.id}`,
          // });
          this.$emit('watchTableFnc', {
            type: 'toItrMaintenancePlan',
            params: { info: scope },
          });
        },
        editNoSearch: () => {
          this.$emit('watchTableFnc', {
            type: 'editNoSearch',
            params: { info: scope },
          });
        },
        deleteNoSearch: async () => {
          if (!(await this.$platform.confirm(t('common.base.tip.aboutToDelete')))) return;
          let arr = _.cloneDeep(this.page.list);
          let index = param.$index;
          arr[index] = { ...arr[index], delete: 1 };
          this.backPageList = arr;
          this.page.list.splice(index, 1);
          this.page.total--;
        },
        showLinkPartList: () => {
          this.$emit('watchTableFnc', {
            type: 'showLinkPartList',
            params: { info: scope },
          });
        },
        editLinkPart: () => {
          this.$emit('watchTableFnc', {
            type: 'editLinkPart',
            params: { info: scope },
          });
        },
        delLinkPart: () => {
          this.$emit('watchTableFnc', {
            type: 'delLinkPart',
            params: { info: scope },
          });
        },
        delProductMenuLinkTable: () => {
          this.$emit('watchTableFnc', {
            type: 'delProductMenuLinkTable',
            params: { info: scope },
          });
        },
        editLinkServerResources: () => {
          this.$emit('watchTableFnc', {
            type: 'editLinkServerResources',
            params: { info: scope },
          });
        },
        delLinkServerResources: () => {
          this.$emit('watchTableFnc', {
            type: 'delLinkServerResources',
            params: { info: scope },
          });
        },
        delLinkMaintenancePlan: () => {
          this.$emit('watchTableFnc', {
            type: 'delLinkMaintenancePlan',
            params: { info: scope },
          });
        },
        toItrBomView: () => {
          if (!param) return console.log('Bomid为空');
          // this.$platform.openTab({
          //   id: `itrBom_view_${param}`,
          //   title: 'Bom详情',
          //   close: true,
          //   reload: true,
          //   url: `/partV2/category/itrBom/view?id=${param}`,
          // });

          openAccurateTab({
            type: PageRoutesTypeEnum.PageCategoryItrBomView,
            key: param,
            params: `id=${param}`,
            reload: true,
          })
        },
        changeBomState: () => {
          scope.enable = !scope.enable;
          columns.disabled = true;
          this.$emit('watchTableFnc', {
            type: 'changeBomState',
            params: { info: scope },
            callBack: () => {
              columns.disabled = false;
            },
          });
        },
      };
      try {
        typeEnum[type]();
      } catch (error) {
        console.warn(error, 'error try catch');
      }
    },
    addFnc() {
      try {
        this.tableSetting.addFnc();
      } catch (error) {
        console.warn(error, 'error try catch');
      }
    },
    async delFnc() {
      if (!this.multipleSelection.length) {
        return this.$platform.alert(
          `${
            this.tableSetting.delTipNullText
              ? this.tableSetting.delTipNullText
              : t('common.base.tip.selectDeleteItem')
          }`
        );
      }
      try {
        if (
          !(await this.$platform.confirm(
            `${
              this.tableSetting.delTipText
                ? this.tableSetting.delTipText
                : '确定要删除已选择的选项？'
            }`
          ))
        )
          return;
        let ids;
        if (this.tableSetting.delFncParams)
          ids = await this.tableSetting.delFncParams(this.multipleSelection);
        else ids = this.multipleSelection.map((p) => p.id).join(',');
        if (!ids) return;
        this.loading = true;
        const res = await this.tableSetting.delFnc(ids);
        this.loading = false;
        if (!res || res.code || res.status)
          return this.$platform.notification({
            title: '失败',
            type: 'error',
            message: res.message || '发生未知错误',
          });
        this.$message.success(res.message);
        this.multipleSelection = [];
        this.search();
      } catch (e) {
        this.loading = false;
        console.error('e', e);
      }
    },
    alterList() {
      return {
        //  只适用于不分页的表格 用于动态改变列表数据
        merge: (data = []) => {
          try {
            data.forEach(
              (item, index) =>
                (item['id'] = `field_${this.page.list.length + index}`)
            );
            this.page.list = [...this.page.list, ...data];
            this.backPageList = _.cloneDeep(this.page.list);
            console.log(data, 'merge');
            this.page.total += data.length;
          } catch (error) {
            console.warn(error, 'error try catch');
          }
        },
        edit: (data = {}) => {
          if (!data.hasOwnProperty('id')) return;
          this.page.list.forEach((item, index) => {
            if (item.id == data.id) {
              this.$set(this.page.list, index, data);
            }
          });
          this.backPageList.forEach((item, index) => {
            if (item.id == data.id) {
              this.$set(this.backPageList, index, data);
            }
          });
        },
        get: () => {
          return new Promise((resolve) => {
            resolve(this.page.list);
          });
        },
        getBackUp: () => {
          return new Promise((resolve) => {
            resolve(this.backPageList);
          });
        },
        getMultipleSelection: () => {
          return Promise.resolve(this.multipleSelection);
        },
        setMultipleSelection: (data = []) => {
          this.multipleSelection = data;
        },
      };
    },
    /**
     * @des 表格头部className的函数
     */
    tableColumnClassName(column) {
      let first = this.columns.find((item) => item.show);
      return [
        column.field == 'name' ? 'product-name-superscript-td' : '',
        first && first.field == column.field && this.tableSetting.haveTreeTable
          ? 'tree-header'
          : '',
      ].join(' ');
    },
    /**
     * @des RBRT设备关联设备截止时间计算
     */
    transProductLinkPartEndTime(row) {
      let res_ = '';
      try {
        let start1 = row.createTime || 0;
        let start2 = row.warranty;
        if (start1 && start2) {
          start2 = `${start2}`.indexOf('月') > 0 ? start2.replace('月', '') : start2;
          start1 = `${start1}`.indexOf('-') > -1
            ? start1.replace(new RegExp('-', 'g'), '/')
            : start1;
          start1 = safeNewDate(start1);
          res_ = start1.setMonth(start1.getMonth() + start2 * 1);
          res_ = formatDate(res_, 'YYYY-MM-DD');
        }
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      return res_;
    },
    /**
     * @des RBRT设备关联设备状态计算
     */
    transProductLinkPartState(row) {
      const stateEnum = {
        online: '在保',
        off: '保外',
      };
      let end = `${this.transProductLinkPartEndTime(row)} 23:59:59`;
      if (end) {
        if (safeNewDate(end).getTime() > safeNewDate().getTime())
          return stateEnum.online;
        return stateEnum.off;
      }
      return '';
    },
  },
};
</script>
<style lang="scss" scoped>

.base-with-input {
  width: 400px !important;
  .el-input-group__append{
    border-radius: 0;
  }
}
.base-selection-bar-container{
  margin-bottom: 0;
}
</style>
<style lang="scss">
.base-list {
  &-header {
    background: #ffffff;
    box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.06);
    border-radius: 4px;
    margin-bottom: 12px;
    border-top: none;

    &-seach {
      padding: 16px;

      .seach {
        justify-content: flex-end;
        padding-right: 16px;

        // .advanced-search-visible-btn {
        //   width: 98px;
        //   height: 32px;
        //  background: $color-primary-light-1;
        //   border-radius: 4px;
        //   border: 1px solid $color-primary-light-2;
        //   font-size: 14px;
        //   color: $color-primary-light-6;
        //   line-height: 32px;
        //   text-align: center;
        //   cursor: pointer;
        // }
        .advanced-search-visible-btn {
          background: #fff;
          border-color: $color-primary;
          @include fontColor();
          font-size: 14px;
          height: 32px;
          line-height: 32px;
          padding: 0 13px;
          white-space: nowrap;

          &:hover {
            cursor: pointer;
          }
        }
      }
    }

    &-nav {
      > div {
        position: relative;
        border-top: 1px solid #f5f5f5;
        .state {
          padding-top: 4px;
          padding-left: 11px;
          width: 90px;
          font-weight: 500;
          background-color: #fafafa;
        }
        .element-icon i {
          position: absolute;
          right: 12px;
          top: 6px;
        }
        .list {
          width: 90%;
          overflow: hidden;
          // height: 30px;
          .list-item {
            > div {
              padding-left: 11px;
              font-size: 13px;
              width: 130px;
              height: 30px;
              overflow-y: hidden;
              color: #808080;
              line-height: 30px;
              cursor: pointer;
              &:hover {
                color: #333;
              }
            }
          }
        }
      }
    }
  }
}
.product-list-container {
  height: 100%;
  overflow: auto;
}

.product-columns-dropdown-menu {
  max-height: 300px;
  overflow: auto;
  .el-dropdown-menu__item {
    padding: 0;
  }
  .el-checkbox {
    width: 100%;
    padding: 5px 15px;
    margin: 0;
  }
}

.product-list-container .product-list-section {
  padding-top: 10px;
}

// operation
.product-list-container .product-list-section .operation-bar-container {
  background: #fff;
  border-radius: 3px 3px 0 0;
  display: flex;
  justify-content: space-between;
  padding: 10px;

  .top-btn-group .base-button {
    margin-right: 5px;
  }

  .action-button-group {
    .base-button {
      margin-left: 5px;
    }
  }

  .el-dropdown-btn {
    padding: 0 15px;
    line-height: 31px;
    display: inline-block;
    background: $color-primary-light-9;
    color: $text-color-primary;
    outline: none;
    margin-left: 5px;
    .iconfont {
      margin-left: 5px;
      font-size: 12px;
    }

    &:hover {
      cursor: pointer;
      color: #fff;
      background: $color-primary;
    }
  }
}

// table
.el-table {
  border: none;
  .cell {
    display: flex !important;
    flex-wrap: wrap !important;
    align-items: center !important;
  }
  .tree-header {
    .cell {
      display: flex;
      flex-wrap: nowrap;
      align-items: center;
    }
  }
  .el-table__expand-icon {
    display: flex;
    align-items: center;
    margin-right: 5px;
    width: auto;
    height: auto;
  }
}
.el-table--small th,
.el-table--small td {
  height: 40px;
  padding: 3px 0;
}
.product-list-container .product-table {
  padding: 10px;

  &:before {
    height: 0;
  }

  .goods-img-list {
    height: 100%;
    img {
      width: 32px;
      height: 32px;
      margin-right: 4px;
      cursor: pointer;
    }
  }

  .product-table-header th {
    background: #f5f5f5;
    color: $text-color-primary;
    font-weight: normal;
  }

  th {
    color: #606266;
    font-size: 14px;
  }
  td {
    color: #909399;
    font-size: 13px;
  }

  .view-detail-btn {
    color: $color-primary;
  }

  .select-column .el-checkbox {
    position: relative;
    top: 3px;
  }
}

.product-list-container .table-footer {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  background: #fff;
  border-radius: 0 0 3px 3px;
  flex-wrap: wrap;

  .list-info {
    font-size: 13px;
    line-height: 32px;
    margin: 0;
    color: #767e89;

    .iconfont {
      position: relative;
      top: 1px;
    }

    .product-selected-count {
      color: $color-primary;
      padding: 0 3px;
      width: 15px;
      text-align: center;
      cursor: pointer;
      font-size: 13px;
    }
  }

  .el-pagination__jump {
    margin-left: 0;
  }
}

// select panel
.product-list-container .product-selected-panel {
  font-size: 14px;
  height: calc(100% - 51px);

  .product-selected-tip {
    padding-top: 80px;

    img {
      display: block;
      width: 160px;
      margin: 0 auto;
    }

    p {
      text-align: center;
      color: $text-color-regular;
      margin: 8px 0 0 0;
      line-height: 20px;
    }
  }

  .product-selected-list {
    height: 100%;
    padding: 10px;
    overflow-y: auto;

    .product-selected-row {
      display: flex;
      flex-flow: row nowrap;
      align-items: center;
      border-bottom: 1px solid #ebeef5;
      font-size: 13px;

      &:hover {
        background-color: #f5f7fa;

        .product-selected-delete {
          visibility: visible;
        }
      }
    }

    .product-selected-head {
      background-color: #f0f5f5;
      color: #333;
      font-size: 14px;
    }

    .product-selected-sn {
      padding-left: 10px;
      width: 100%;
      @include text-ellipsis;
    }

    .product-selected-name {
      padding-left: 10px;
      flex: 1;
      @include text-ellipsis;
    }

    .product-selected-delete {
      width: 36px;
    }

    .product-selected-row button.product-selected-delete {
      padding: 0;
      width: 36px;
      height: 36px;
      border: none;
      background-color: transparent;
      outline: none;
      color: #646b78;
      visibility: hidden;

      i {
        font-size: 14px;
      }

      &:hover {
        color: #e84040;
      }
    }
  }
}

// advanced search form

.base-import-warn {
  p {
    margin: 0;
  }
}

// superscript
.product-name-superscript-td {
  padding: 0 !important;
  & > div {
    height: 31px;
    line-height: 31px !important;
    a {
      display: inline-block;
      height: 31px;
      line-height: 31px;
    }
  }
}

.product-panel {
  .base-panel-title {
    h3 {
      display: flex;
      justify-content: space-between;
    }
    .product-panel-btn {
      cursor: pointer;
      &:hover {
        color: $color-primary;
      }
    }
  }
}
.el-table .cell {
  line-height: 31px;
}

//
.batch-editing-customer-dialog {
  .base-modal-body {
    padding: 10px 30px 0;
  }

  .form-name,
  .form-item label {
    width: 70px;
    padding: 0;
    line-height: 32px;
    margin-right: 10px;
  }

  .el-select {
    width: 100%;
  }

  .item {
    display: flex;
    justify-content: space-between;
    line-height: 32px;
    div {
      flex-grow: 1;
      .el-select {
        width: 100%;
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
  }
}

.form-item {
  .el-checkbox {
    width: 100%;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.el-table-column--selection {
  .cell {
    display: flex;
    align-items: center;
    justify-content: center;
    .el-checkbox {
      margin-bottom: 0;
    }
  }
}
</style>
